package com.bk.bands.template;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import com.bk.bands.model.Band;
import com.bk.bands.model.Template;
import com.google.common.collect.ForwardingCollection;

@XmlRootElement(namespace = "http://com.bk.docs", name = "template")
@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
@XmlType(name = "template", namespace = "http://com.bk.docs", propOrder = {
   "styles",
   "header",
   "bands",
   "footer"
})
public class XmlTemplate
{
   protected XmlStyles styles;

   protected XmlFields header;

   protected List<XmlBand> xmlBands = new LinkedList<XmlBand>();

   protected ForwardingCollection<XmlBand> xmlBandsDecorator = new ForwardingCollection<XmlBand>()
   {

      @Override
      protected List<XmlBand> delegate()
      {
         return xmlBands;
      }

       public boolean add(XmlBand element)
       {
          template.getBands().add(element.getBand());
          return super.add(element);
       }
   };


   protected XmlFields footer;

   private Template template;

   public XmlTemplate()
   {
      template = new Template();
      template.setBands(new LinkedList<Band>());
   }

   @XmlElement(namespace = "http://com.bk.docs", required = true)
   public XmlStyles getStyles()
   {
      return styles;
   }

   public void setStyles(XmlStyles styles)
   {
      this.styles = styles;
      template.setStyles(styles.getStyles());
   }

   @XmlElement(namespace = "http://com.bk.docs", required = true, nillable = true)
   public XmlFields getHeader()
   {
      return header;
   }


   public void setHeader(XmlFields headerFields)
   {
      this.header = headerFields;
      template.setHeader(header.getFields());
   }

   @XmlElement(namespace = "http://com.bk.docs", required = true, name="band")
   public Collection<XmlBand> getBands()
   {
      return xmlBandsDecorator;
   }

   @XmlElement(namespace = "http://com.bk.docs", required = true, nillable = true)
   public XmlFields getFooter()
   {
      return footer;
   }


   public void setFooter(XmlFields footerFields)
   {
      this.footer = footerFields;
      template.setFooter(footer.getFields());
   }

   public XmlStyle findStyle(String styleName)
   {
      for(XmlStyle style : styles.getContent())
      {
         if(style.getName().equals(styleName))
            return style;
      }
      return null;
   }

   public Template getTemplate()
   {
      return template;
   }
}
